<?php
namespace app\api\controller\damp;
/***
 *      ┌─┐       ┌─┐
 *   ┌──┘ ┴───────┘ ┴──┐
 *   │                 │
 *   │       ───       │
 *   │  ─┬┘       └┬─  │
 *   │                 │
 *   │       ─┴─       │
 *   │                 │
 *   └───┐         ┌───┘
 *       │         │    神兽保佑代码没有bug
 *       │         │
 *       │         │
 *       │         └──────────────┐
 *       │                        │
 *       │                        ├─┐
 *       │                        ┌─┘
 *       │                        │
 *       └─┐  ┐  ┌───────┬──┐  ┌──┘
 *         │ ─┤ ─┤       │ ─┤ ─┤
 *         └──┴──┘       └──┴──┘
 *              订单控制器
 */
use app\common\service\Redis;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\Request;
use app\BaseController;
use app\common\controller\ApiController;
use think\App;

class ItemOrder extends ApiController
{

    public function initialize()
    {
        parent::initialize();
        $this->curl = app('app\common\service\CurlServer');
        $this->cart = app('app\common\model\mall\ItemCart');
        $this->store = app('app\common\model\mall\Store');
        $this->store_address = app('app\common\model\mall\StoreAddress');
        $this->item = app('app\common\model\mall\Item');
        $this->itemSku = app('app\common\model\mall\ItemSku');
        $this->user = app('app\common\model\user\WxUsers');
        $this->order = app('app\common\model\mall\ItemOrder');
        $this->coupon = app('app\common\model\mall\Coupon');
        $this->user_coupon = app('app\common\model\user\UserCoupon');
        $this->order_list = app('app\common\model\mall\ItemOrderList');
        $this->order_refund = app('app\common\model\mall\ItemOrderRefund');
        $this->order_subscribe = app('app\common\model\mall\ItemOrderSubscribe');
        $this->ali_pay = app('app\common\service\AliPay');
        $this->configuration = app('app\common\model\system\Configuration');
    }

    /**
     * 立即购买生成订单
     * @param Request $request
     * @return \think\response\Json
     */
    public function add_order(Request $request)
    {
        $params = $request->param();
        try {
            Db::startTrans();
            $this->validate($params , [
                'item_id|商品id' => 'require' ,
                'sku_id|规格' => 'require' ,
                'number|数量' => 'require' ,
                'key|用户登陆信息' => 'require' ,
                'is_market|活动状态' => 'require'
            ]);
            //检查商品的状态
            $item_info = $this->item->where(['id' => $params['item_id'] , 'status' => 1])->find();

            if (!$item_info) throw new \Exception('商品状态异常');

            //查询规格
            $sku_info = $this->itemSku->where('id' , $params['sku_id'])->find();

            if (!$sku_info) throw new \Exception('商品规格状态异常');

            if ($sku_info['inventory'] < $params['number'])
                throw new \Exception('商品库存不足');


            $sn = date('Ymd') . random_int(100000 , 999999);

            //生成主订单号
            $master_order = 'M_' . $sn;

            //订单金额
            $item_info['is_discount'] == 1 && $amount = round($sku_info['goods_price'] * $request->user_cost * $params['number'] , 2);
            $item_info['is_discount'] != 1 && $amount = round($sku_info['goods_price'] * $params['number'] , 2);

            //获取优惠券额度
            if ($params['coupon_id']) {
                $coupon_info = $this->user_coupon->with('coupon')->where('id' , $params['coupon_id'])->find();
                $coupon_price = $coupon_info->coupon->discount_price;
            } else {
                $coupon_price = 0;
            }

            $old_amount = round($sku_info['goods_price'] * $params['number'] , 2);
            $amount = $amount - $coupon_price;
            //获取折扣力度
            $item_info['is_discount'] == 1 && $cost = round($sku_info['goods_price'] * ( 1 - $request->user_cost ) * $params['number'] , 2);
            $item_info['is_discount'] != 1 && $cost = 0;
            //订单数据入库
            $orderData = [
                'comment' => $params['comment'] ,
                'type' => $item_info['type'] ,
                'master_order_sn' => $master_order , //主订单号
                'order_sn' => 'S_' . $sn . '1' , //子订单号
                'user_id' => $request->user_id ,
                'coupon_id' => $params['coupon_id'] , //优惠券id
                'coupon_cost' => $coupon_price , //优惠券优惠额度
                'store_id' => $item_info['store_id'] ,
                'discounts' => $cost ,
                'amount' => $amount ,
                'old_amount' => $old_amount ,
            ];

            $this->order->save($orderData);
            //扣除库存
            $this->item->where(['id' => $params['item_id']])->dec('inventory' , $params['number'])->update();
            $this->itemSku->where('id' , $params['sku_id'])->dec('inventory' , $params['number'])->update();
            //商品订单数据入库
            $orderListData = [

                'type' => $item_info['type'] ,
                'item_id' => $params['item_id'] ,
                'sku_id' => $params['sku_id'] ,
                'order_id' => $this->order->id ,
                'number' => $params['number'] ,
                'goods_price' => $sku_info['goods_price'] ,
                'real_price' => $amount ,
                'price' => $amount ,
            ];
            $this->order_list->save($orderListData);
            Db::commit();
            return json(['code' => 200 , 'msg' => '生成订单成功']);

        } catch ( \Exception $e ) {
            Db::rollback();

            return json(['code' => 202 , 'msg' => $e->getMessage()]);

        }
    }

    /**
     * 购物车生成订单
     * @param Request $request
     * @return \think\response\Json
     */
    public function add_cart_order(Request $request)
    {
        $params = $request->param();
        try {
            Db::startTrans();
            $this->validate($params , [
                'cart_id|购物车' => 'require' ,
                'key|用户登陆信息' => 'require' ,
            ]);

            $item_lists = $this->cart->whereIn('id' , $params['cart_id'])->select()->toArray();
            $store_id = $this->cart->whereIn('id' , $params['cart_id'])->distinct(true)->column('store_id');

            //设定各商家订单总额，优惠券金额，折扣金额初始值
            foreach ($store_id as $k => $v) {
                $amount[$v] = 0;
                $old_amount[$v] = 0;
                $cost[$v] = 0;
                $coupon_price[$v] = 0;
            }

            $sn = date('Ymd') . random_int(100000 , 999999);

            //生成主订单号
            $master_order = 'M_' . $sn;

            //dd($item_lists);
            //组装数据和拆分订单 一个商户一个订单
            foreach ($item_lists as $k => $v) {


                //检查商品信息
                $item_info = $this->item->where(['id' => $v['item_id'] , 'status' => 1])->find();

                if (!$item_info) throw new \Exception('商品状态异常');

                //查询规格
                $sku_info = $this->itemSku->where('id' , $v['sku_id'])->find();

                if (!$sku_info) throw new \Exception('商品规格状态异常');

                if ($sku_info['inventory'] < $v['number'])
                    throw new \Exception('商品库存不足');

                //扣除库存
                $this->item->where(['id' => $v['item_id']])->dec('inventory' , $v['number'])->update();
                $this->itemSku->where('id' , $v['sku_id'])->dec('inventory' , $v['number'])->update();

                //订单优惠后金额

                $item_info['is_discount'] == 1 && $amount[$item_info['store_id']] += round($sku_info['goods_price'] * $request->user_cost * $v['number'] , 2);
                $item_info['is_discount'] != 1 && $amount[$item_info['store_id']] += round($sku_info['goods_price'] * $v['number'] , 2);

                //订单实付金额
                $old_amount[$item_info['store_id']] +=round($sku_info['goods_price'] * $v['number'] , 2);

                //获取子订单规格实付价
                $item_info['is_discount'] == 1 && $real_price[$v['item_id']] = round($sku_info['goods_price'] * $request->user_cost * $v['number'] , 2);
                $item_info['is_discount'] != 1 && $real_price[$v['item_id']] = round($sku_info['goods_price'] * $v['number'] , 2);

                //获取优惠券额度
                if ($params['coupon_id']) {
                    $coupon_info = $this->user_coupon->with('coupon')->where('id' , $params['coupon_id'])->find();

                    //判断是否为平台优惠券  平台优惠券按比例划分优惠折扣

                    if ($coupon_info->coupon->type == 1) {
                        $coupon_price[0] =  $coupon_info->coupon->discount_price; //平台优惠券金额
                    } else {

                        //获取商家优惠券额度
                        $coupon_price[$coupon_info->store_id] = $coupon_info->coupon->discount_price;

                    }

                }

                //获取折扣力度
                $cost[$item_info['store_id']] = 0;
                $item_info['is_discount'] == 1 && $cost[$item_info['store_id']] += round($sku_info['goods_price'] * ( 1 - $request->user_cost ) * $v['number'] , 2);
                $item_info['is_discount'] != 1 && $cost[$item_info['store_id']] += 0;


                //获取总额
                $amount[$v['store_id']] = $amount[$v['store_id']] - $coupon_price[$v['store_id']];

                //订单主数据.
                $orderData[$v['store_id']] = [
                    'type' => $item_info['type'] ,
                    'master_order_sn' => $master_order , //主订单号
                    'order_sn' => 'S_' . $sn . $item_info['store_id'] , //子订单号
                    'user_id' => $request->user_id ,
                    'store_id' => $v['store_id'] ,
                    'discounts' => $cost[$v['store_id']] , //折扣金额
                    'app_id' => $params['app_id'] ,
                    'amount' => $amount[$v['store_id']] ,
                    'old_amount' => $old_amount[$v['store_id']] ,
                    'coupon_id' => $params['coupon_id'] , //优惠券id
                    'coupon_cost' => $coupon_price[$v['store_id']] ?? 0 , //优惠券优惠额度
                    'create_time' => time() ,
                ];
                //订单商品数据
                $list[$v['store_id']][$v['item_id']] = [
                    'type' => $item_info['type'] ,
                    'item_id' => $v['item_id'] ,
                    'sku_id' => $v['sku_id'] ,
                    'app_id' => $params['app_id'] ,
                    'number' => $v['number'] ,
                    'goods_price' => $sku_info['goods_price'] ,
                    'price' => $sku_info['goods_price'] * $v['number'] ,
                    'real_price' => $real_price[$v['item_id']],
                    'create_time' => time() ,
                ];
                //拼装数据
                $orderData[$v['store_id']]['order_list'] = $list[$v['store_id']];

            }

            //订单数据入库
            foreach ($orderData as $k => $v) {

                $order_id = Db::name('item_order')->strict(false)->insertGetId($v);



                foreach ($v['order_list'] as $key => $value) {

                    //划分商家优惠券金额
                    if($coupon_price[$k] > 0){
                      $ratio = round($value['price'] / $v['old_amount'],2) ;
                      $value['real_price'] = $value['real_price'] - $coupon_price[$k] * $ratio;


                    }elseif($coupon_price[0] >0){ //划分平台优惠券金额
                        $ratio = round($value['price'] / $v['old_amount'],2) ;
                        $value['real_price'] = $value['real_price'] - $coupon_price[0] * $ratio;
                    }

                    $value['order_id'] = $order_id;

                    Db::name('item_order_list')->strict(false)->insert($value);

                }
            }

            //清空购物车
            $rows = $this->cart->whereIn('id' , $params['cart_id'])->select();
            $rows && $rows->delete();
            Db::commit();
            return json(['code' => 200 , 'msg' => '生成订单成功']);

        } catch ( \Exception $e ) {
            Db::rollback();

            return json(['code' => 202 , 'msg' => $e->getMessage()]);

        }
    }


    /**
     * 订单详情
     * @param Request $request
     * @return \think\response\Json
     */
    public function order_detail(Request $request)
    {
        $params = $request->param();
        try {
            Db::startTrans();
            $this->validate($params , [
                'order_id|订单id' => 'require' ,
                'key|用户登陆信息' => 'require' ,
            ]);

            $order_info = $this->order
                ->where('id' , $params['order_id'])
                ->with(['Lists' => function ($query) {
                    $query->with(['Goods' , 'GoodsSku']);
                } , 'Store' , 'User' , 'Address'])
                ->find()->toArray();

            return json(['code' => 200 , 'msg' => '成功' , 'data' => ['data' => $order_info]]);

        } catch ( \Exception $e ) {

            return json(['code' => 202 , 'msg' => $e->getMessage()]);

        }
    }

    /**
     * 订单列表
     * @param Request $request
     * @return \think\response\Json
     */
    public function order_list(Request $request)
    {
        $params = $request->param();
        try {
            Db::startTrans();
            $this->validate($params , [
                'status|订单状态' => 'require' ,
                'key|用户登陆信息' => 'require' ,
            ]);

            $where['type'] = $params['type'];
            //1：全部；2：待付款；3：待发货；4：待收货；5：已完成；6：退款售后
            //type：1:线下商品；2：线上商品
            switch ($params['status']) {
                case 1:
                    $where['status'] = [];
                    break;
                case 2:
                    $where['status'] = 0;
                    break;
                case 3:
                    $where['status'] = 1;
                    break;
                case 4:
                    $where['status'] = 2;
                    break;
                case 5:
                    $where['status'] = 8;
                    break;
                case 6:
                    $where['status'] = ['in' , [4 , 5 , 6 , 9]];
                    break;
            }
            $order_list = $this->order
                ->where($where)
                ->with(['Lists' => function ($query) {
                    $query->with(['Goods' , 'GoodsSku']);
                } , 'Store'])
                ->select()
                ->paginate($request->param('limit' , 5));
            $data = [
                'total' => $order_list->total() ,         // 总记录数
                'current_page' => $order_list->currentPage() ,   // 当前页码
                'per_page' => $order_list->listRows() ,      // 每页记录数
                'data' => $order_list->items()          // 分页数据
            ];
            return json(['code' => 200 , 'msg' => '成功' , 'data' => ['data' => $data]]);

        } catch ( \Exception $e ) {

            return json(['code' => 202 , 'msg' => $e->getMessage()]);

        }
    }


    /**
     * 订单操作
     * @param Request $request
     * 1：取消订单；2：删除订单；3:申请退款;4:申请退货退款;5:撤销申请;6:预约；7核销；8：已收货
     * @return \think\response\Json
     */
    public function action_order(Request $request)
    {
        $params = $request->param();
        try {
            Db::startTrans();
            $this->validate($params , [
                'order_id|订单Id' => 'require' ,
                'key|用户登陆信息' => 'require' ,
            ]);

            $where = ['user_id' => $request->user_id , 'id' => $params['order_id']];
            $order_info = $this->order->where($where)->find();
            //type  1：取消订单；2：删除订单；3:申请退款;4:申请退货退款;5:撤销申请;6:预约；7核销；8：已收货
            switch ($params['type']) {
                case 1:
                    if ($order_info->status != 0) throw new \Exception('订单状态异常，无法取消');
                    $order_info->update(['status' => 7]);
                    break;
                case 2:
                    if ($order_info->status != 7) throw new \Exception('订单状态异常，无法删除');
                    $order_info->delete();
                    break;
                case 3:
                    $this->validate($params , [
                        'sub_order_id|子订单Id' => 'require' ,
                    ]);
                    $sub_order_info = $this->order_list->find($params['sub_order_id']);
                    if ($sub_order_info->status == 0) throw new \Exception('售后已申请');

                    $order_info->save(['status' => 9]);
                    $this->order_refund->save([
                        'order_id' => $sub_order_info['order_id'] ,
                        'sub_order_id' => $params['sub_order_id'] ,
                        'type' => 1 ,
                        'status' => 0 ,
                        'user_id' => $order_info['user_id'] ,
                        'item_id' => $sub_order_info['item_id'] ,
                        'sku_id' => $sub_order_info['sku_id'] ,
                        'number' => $sub_order_info['number'] ,
                        'comment' => $params['comment'] ,
                    ]);
                    $sub_order_info->save(['status' => 0]);
                    break;
                case 4:
                    $this->validate($params , [
                        'sub_order_id|子订单Id' => 'require' ,
                    ]);
                    $sub_order_info = $this->order_list->find($params['sub_order_id']);
                    $order_info->save(['status' => 9]);

                    if ($sub_order_info->status == 0) throw new \Exception('售后已申请');

                    $this->order_refund->save([
                        'order_id' => $sub_order_info['order_id'] ,
                        'sub_order_id' => $params['sub_order_id'] ,
                        'type' => 2 ,
                        'status' => 0 ,
                        'user_id' => $order_info['user_id'] ,
                        'item_id' => $sub_order_info['item_id'] ,
                        'sku_id' => $sub_order_info['sku_id'] ,
                        'number' => $sub_order_info['number'] ,
                        'comment' => $params['comment'] ,
                    ]);
                    $sub_order_info->save(['status' => 0]);
                    break;
                case 5:
                    $this->validate($params , [
                        'sub_order_id|子订单Id' => 'require' ,
                    ]);
                    $sub_order_info = $this->order_list->find($params['sub_order_id']);

                    if ($sub_order_info->status == 4) throw new \Exception('售后已撤销');

                    $order_refund_info = where(['order_id' => $sub_order_info['order_id'] , 'sub_order_id' => $params['sub_order_id']])->find();
                    $order_refund_info->save(['status' => 5]);
                    $sub_order_info->save(['status' => 4]);
                    break;
                case 6:
                    $this->validate($params , [
                        'sub_order_id|子订单Id' => 'require' ,
                        'time|预约日期' => 'require' ,
                        'address_id|商家地址Id' => 'require' ,
                    ]);
                    $sub_order_info = $this->order_list->find($params['sub_order_id']);
                    $order_info->save(['status' => 10]);

                    if ($sub_order_info->status != 4) throw new \Exception('订单状态异常');

                    $this->order_subscribe->save([
                        'order_id' => $sub_order_info['order_id'] ,
                        'sub_order_id' => $params['sub_order_id'] ,
                        'user_id' => $order_info['user_id'] ,
                        'store_id' => $order_info['store_id'] ,
                        'item_id' => $sub_order_info['item_id'] ,
                        'address_id' => $params['address_id'] ,
                        'sku_id' => $sub_order_info['sku_id']
                    ]);
                    $sub_order_info->save(['status' => 6]);
                    break;
                case 7:
                    $sub_order_info = $this->order_list->find($params['sub_order_id']);

                    $is_subscribe = $this->item->where('id' , $sub_order_info->item_id)->value('is_subscribe');

                    if ($sub_order_info->status != 6 && $is_subscribe == 1) throw new \Exception('该商品需要先预约');

                    $order_refund_info = where(['order_id' => $sub_order_info['order_id'] , 'sub_order_id' => $params['sub_order_id']])->find();

                    $order_refund_info->save(['status' => 11]);
                    $sub_order_info->save(['status' => 7]);
                    break;
                case 8:
                    if ($order_info->status != 2) throw new \Exception('订单状态异常，无法确认收货');
                    $order_info->update(['status' => 3]);
                    break;

            }
            Db::commit();
            return json(['code' => 200 , 'msg' => '成功']);

        } catch ( \Exception $e ) {
            Db::rollback();
            return json(['code' => 202 , 'msg' => $e->getMessage()]);

        }
    }


    /**
     * 预览订单信息
     * @param Request $request
     * //type1：立即购买；购物车提交：3:预约商品
     * @return \think\response\Json
     */
    public function show_order_info(Request $request)
    {
        $params = $request->param();
        try {

            switch ($params['type']) {
                case 1:
                    $this->validate($params , [
                        'item_id|商品id' => 'require' ,
                        'sku_id|规格' => 'require' ,
                        'number|数量' => 'require' ,
                        'key|用户登陆信息' => 'require' ,
                        'is_market|商品状态' => 'require' ,
                    ]);
                    //检查商品的状态
                    $item_info = $this->item->where(['id' => $params['item_id'] , 'status' => 1])
                        ->field('title,thumb,goods_price,inventory,store_id,is_discount')
                        ->find()->toArray();

                    if (!$item_info) throw new \Exception('商品状态异常');

                    //查询规格
                    $sku_info = $this->itemSku->where('id' , $params['sku_id'])->find()->toArray();

                    if (!$sku_info) throw new \Exception('商品规格状态异常');

                    if ($sku_info['inventory'] < $params['number'])
                        throw new \Exception('商品库存不足');

                    $lists = $this->store->where('id' , $item_info['store_id'])->field('id,name')->select()->toArray();

                    foreach ($lists as $k => $v) {
                        $lists[$k][$k] = [['number' => $params['number'] , 'item' => $item_info , 'sku' => $sku_info]];

                    }

                    //获取总价
                    $item_info['is_discount'] == 1 && $amount = round($sku_info['goods_price'] * $request->user_cost * $params['number'] , 2);
                    $item_info['is_discount'] != 1 && $amount = round($sku_info['goods_price'] * $params['number'] , 2);
                    //获取优惠券信息
                    if ($params['is_market'] != 1) {
                        $map[] = ['store_id' , '=' , $item_info['store_id']]; //不为空的
                        $map[] = ['coupon_type' , '=' , 1]; //不为空的
                        $coupon_list = $this->user_coupon->with('coupon')
                            ->whereTime('expire_time' , '>' , time())
                            ->where('coupon_price' , '<' , $amount)
                            ->where(function ($query) use ($map) {
                                $query->whereOr($map);
                            })->select()->toArray();

                    } else {
                        $coupon_list = [];
                    }

                    $lists['amount'] = $amount;
                    $lists['coupon_list'] = $coupon_list;

                    break;
                case 2:
                    $this->validate($params , [
                        'cart_id|购物车' => 'require' ,
                        'key|用户登陆信息' => 'require' ,
                    ]);
                    $store_id = $this->cart->column('store_id');
                    $lists = $this->store->whereIn('id' , $store_id)->field('id,name')->select()->toArray();

                    $amount = 0;
                    foreach ($lists as $k => $v) {
                        $lists[$k][] = $this->cart->where('user_id' , $request->user_id)
                            ->with(['item' , 'sku'])
                            ->where('store_id' , $v['id'])
                            ->select()->toArray();

                        //获取当前店铺总价
                        foreach ($lists[$k][0] as $key => $val) {
                            $val['item']['is_discount'] == 1 && $lists[$k][$v['id']]['amount'] = round($val['sku']['goods_price'] * $val['number'] * $request->user_cost , 2);
                            $val['item']['is_discount'] != 1 && $lists[$k][$v['id']]['amount'] = round($val['sku']['goods_price'] * $val['number'] , 2);

                        }
                        //查询达到满减的店铺优惠券

                        $coupon_list[$k] = $this->user_coupon->with('coupon')
                            ->whereTime('expire_time' , '>' , time())
                            ->where('coupon_price' , '<' , $lists[$k][$v['id']]['amount'])
                            ->where(function ($query) use ($v) {
                                $query->whereOr(['store_id' => $v['id'] , 'coupon_type' => 1]);
                            })->select()->toArray();
                        $amount += $lists[$k][$v['id']]['amount'];
                        //dd($this->user_coupon->getLastSql());
                    }

                    $lists['amount'] = $amount;
                    $lists['coupon_list'] = $coupon_list;

                    break;
                case 3:
                    $this->validate($params , [
                        'key|用户登陆信息' => 'require' ,
                        'order_id|订单id' => 'require' ,
                        'sub_order_id|子订单id' => 'require' ,
                    ]);

                    $lists['sub_order_info'] = $this->order_list->with(['Goods' , 'GoodsSku'])->find($params['sub_order_id'])->toArray();

                    $lists['address_list'] = $this->store_address->where('store_id' , $lists['sub_order_info']['Goods']['store_id'])->select()->toArray();

                    for ($i = 0; $i < 9; $i++) {

                        $dateArray[$i] = date('Y-m-d' , strtotime(date('Y-m-d') . '+' . $i . 'day'));

                    };
                    $lists['dateArray'] = $dateArray;

                    break;
            }

            return json(['code' => 200 , 'data' => ['list' => $lists]]);

        } catch ( \Exception $e ) {

            return json(['code' => 202 , 'msg' => $e->getMessage()]);

        }
    }
}